// DownloadCompleteReceiver.kt
package com.example.myapplication.update

import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Environment
import android.util.Log
import android.widget.Toast
import androidx.core.content.FileProvider
import androidx.core.net.toUri
import java.io.File

class DownloadCompleteReceiver : BroadcastReceiver() {
    companion object {
        private const val TAG = "DownloadCompleteReceiver"
        private const val APK_NAME = "app-release.apk"
    }

    override fun onReceive(context: Context, intent: Intent) {
        Log.i(TAG, "onReceive called with action: ${intent.action}")
        if (intent.action == DownloadManager.ACTION_DOWNLOAD_COMPLETE) {
            val downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
            Log.i(TAG, "收到下载完成广播，downloadId: $downloadId")
            // 注意：这里需要获取 AutoUpdateApp 实例或者保存的 downloadId 来比较
            Log.i(TAG, "下载完成，开始准备安装程序...")

            try {
                // 尝试通过DownloadManager获取文件
                val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
                val downloadedUri = downloadManager.getUriForDownloadedFile(downloadId)
                if (downloadedUri != null) {
                    Log.i(TAG, "通过DownloadManager获取到URI: $downloadedUri")
                    installApk(context, downloadedUri)
                } else {
                    // todo 回退到文件方式，公共目录寻找方式
                    Log.w(TAG, "无法通过DownloadManager获取URI，尝试文件方式")
                    val downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                    val apkFile = File(downloadDir, APK_NAME)
                    if (apkFile.exists()) {
                        Log.i(TAG, "下载完成，文件路径: ${apkFile.absolutePath}")
                        installApk(context,apkFile)
                    } else {
                        Log.e(TAG, "下载失败，文件不存在")
                        Toast.makeText(context, "下载失败，文件不存在", Toast.LENGTH_SHORT).show()
                    }
                }
            } catch (e: Exception) {
                Log.e(TAG, "处理下载完成时出错", e)
            }finally {
                // 安装管理器会自动管理，文件方式需要
//                deleteExistingApk(context)
            }
        }
    }

    private fun installApk(context: Context, apkUri: Uri) {
        try {
            Toast.makeText(context, "下载完成,请开始安装.", Toast.LENGTH_SHORT).show()
            val installIntent = Intent(Intent.ACTION_VIEW).apply {
                setDataAndType(apkUri, "application/vnd.android.package-archive")
                addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }

            // 检查是否有应用可以处理安装Intent
            if (installIntent.resolveActivity(context.packageManager) != null) {
                context.startActivity(installIntent)
            } else {
                Toast.makeText(context, "未找到安装程序", Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(context, "安装失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }


    private fun installApk(context: Context,apkFile: File) {
        try {
            Log.i(TAG, "准备安装APK: ${apkFile.absolutePath}")

            // 检查文件是否存在
            if (!apkFile.exists()) {
                Log.e(TAG, "APK文件不存在: ${apkFile.absolutePath}")
                Toast.makeText( context, "安装文件不存在", Toast.LENGTH_SHORT).show()
                return
            }

            // 检查文件大小
            Log.i(TAG, "APK文件大小: ${apkFile.length()} bytes")
            if (apkFile.length() == 0L) {
                Log.e(TAG, "APK文件为空")
                Toast.makeText(context, "安装文件损坏", Toast.LENGTH_SHORT).show()
                return
            }

            val intent = Intent(Intent.ACTION_VIEW).apply {
                flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION
            }

            val uri = FileProvider.getUriForFile(
                context,
                "${context.packageName}.provider",
                apkFile
            )

            Log.i(TAG, "文件URI: $uri")

            intent.setDataAndType(uri, "application/vnd.android.package-archive")

            // 检查是否有应用可以处理这个Intent
            val packageManager = context.packageManager
            val activities = packageManager.queryIntentActivities(intent, 0)
            Log.i(TAG, "可处理安装的应用数量: ${activities.size}")

            context.startActivity(intent)
            Log.i(TAG, "已启动安装界面")
        } catch (e: SecurityException) {
            Log.e(TAG, "安全异常，可能缺少安装权限", e)
            Toast.makeText(context, "缺少安装权限，请在设置中允许应用安装权限", Toast.LENGTH_LONG).show()

            // 引导用户到设置页面开启权限
            openInstallPermissionSettings(context)
        } catch (e: Exception) {
            Log.e(TAG, "安装APK失败", e)
            Toast.makeText(context, "安装失败，请手动安装: ${e.message}", Toast.LENGTH_LONG).show()
        }
    }


    /**
     * 删除已存在的APK文件
     */
    private fun deleteExistingApk(context: Context) {
        try {
            val downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)

            // 删除标准文件名
            val apkFile = File(downloadDir, APK_NAME)
            if (apkFile.exists()) {
                apkFile.delete()
                Log.i(TAG, "已删除旧文件: $APK_NAME")
            }

            // 删除可能存在的.zip变体
            val zipFile = File(downloadDir, APK_NAME.substringBeforeLast(".") + ".zip")
            if (zipFile.exists()) {
                zipFile.delete()
                Log.i(TAG, "已删除旧文件: ${zipFile.name}")
            }

            // 删除其他可能的变体
            val files = downloadDir.listFiles { file ->
                file.name.startsWith(APK_NAME.substringBeforeLast(".")) &&
                        (file.name.endsWith(".apk") || file.name.endsWith(".zip"))
            }

            files?.forEach { file ->
                if (file.delete()) {
                    Log.i(TAG, "已删除旧文件: ${file.name}")
                }
            }
            Toast.makeText(context, "安装包删除成功", Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            Log.w(TAG, "删除旧APK文件失败", e)
        }
    }


    /**
     * 引导用户到安装权限设置页面
     */
    private fun openInstallPermissionSettings(context: Context) {
        try {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                val intent = Intent(android.provider.Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES)
                intent.data = "package:${context.packageName}".toUri()
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK

                // 检查是否有应用可以处理这个Intent
                val packageManager = context.packageManager
                if (intent.resolveActivity(packageManager) != null) {
                    context.startActivity(intent)
                    Log.i(TAG, "已引导用户到安装权限设置页面")
                } else {
                    openGeneralSettings(context)
                }
            } else {
                openGeneralSettings(context)
            }
        } catch (e: Exception) {
            Log.e(TAG, "引导用户到安装权限设置页面失败", e)
            openGeneralSettings(context)
        }
    }


    /**
     * 打开应用通用设置页面
     */
    private fun openGeneralSettings(context: Context) {
        try {
            val intent = Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
            intent.data = "package:${context.packageName}".toUri()
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            context.startActivity(intent)
            Log.i(TAG, "已引导用户到应用设置页面")
        } catch (e: Exception) {
            Log.e(TAG, "打开应用设置页面失败", e)
            Toast.makeText(context, "请手动到设置中允许应用安装权限", Toast.LENGTH_LONG).show()
        }
    }

}
